package com.idvert.smsdemo.receivers;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;

import com.apkfuns.logutils.LogUtils;
import com.idvert.smsdemo.models.PhoneMessage;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by jigang.duan on 2017/12/8.
 */

public class SMSBroadcastReceiver extends BroadcastReceiver {

    private MessageListener mMessageListener;
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    public SMSBroadcastReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        LogUtils.d("----> SMSBroadcastReceiver onReceive");

        if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            for (Object pdu : pdus) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
                String sender = smsMessage.getDisplayOriginatingAddress();

                //短信内容
                String content = smsMessage.getDisplayMessageBody();

                long date = smsMessage.getTimestampMillis();
                Date tiemDate = new Date(date);
                @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(tiemDate);

                PhoneMessage phoneMessage = new PhoneMessage(sender, content, time);

                mMessageListener.onReceived(phoneMessage);
                abortBroadcast();
            }
        }

    }

    //回调接口
    public interface MessageListener {
        void onReceived(PhoneMessage phoneMessage);
    }

    public void setOnReceivedMessageListener(MessageListener messageListener) {
        this.mMessageListener = messageListener;
    }
}
